package com.docMan.aspect;

import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import com.docMan.dao.pojo.DocDirectory;
import com.docMan.service.DocDirectoryService;
import com.docMan.utils.CastUtil;
import com.docMan.utils.FinalConfig;

@Component("uploadFileAspect")
@Aspect
@EnableAspectJAutoProxy
public class UpLoadFileAspect {
	private DocDirectoryService docDirectoryService;
	private HttpSession httpSession;

	@Autowired
	public void setHttpSession(HttpSession httpSession) {
		this.httpSession = httpSession;
	}

	@Autowired
	public void setDocDirectoryService(DocDirectoryService docDirectoryService) {
		this.docDirectoryService = docDirectoryService;
	}

	@Pointcut("execution(* com.docMan.service.impl.DocFileServiceImpl.createFiles(..))")
	public void aspect() {

	}

	@Before(value = "aspect()")
	public void before(JoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
		System.out.println(CastUtil.castString(httpSession
				.getAttribute(FinalConfig.PersonalDirId)));
		
		int uploadDirId=CastUtil.castInt(args[2]);
		int type=CastUtil.castInt(args[3]);
		int personalDirId=CastUtil.castInt(httpSession.getAttribute(FinalConfig.PersonalDirId));
		if(CastUtil.castBoolean(httpSession.getAttribute(FinalConfig.is_admin),false)){
			httpSession.setAttribute(FinalConfig.canUploadFile2Dir, true);
		}else{
			httpSession.setAttribute(FinalConfig.canUploadFile2Dir, false);
		}
		if(type==FinalConfig.FILE_IN_DIRECTORY){
			if(uploadDirId==personalDirId){
				httpSession.setAttribute(FinalConfig.canUploadFile2Dir, true);
			}else{
				DocDirectory docDirectory=docDirectoryService.getById(uploadDirId);
				String[] pathIds=docDirectory.getPath().split(FinalConfig.path_split);
				for (String id : pathIds) {
					if(CastUtil.castInt(id)==personalDirId){
						httpSession.setAttribute(FinalConfig.canUploadFile2Dir, true);
					}
				}
			}
		}else{
			if(CastUtil.castBoolean(httpSession.getAttribute(FinalConfig.is_admin))){
				httpSession.setAttribute(FinalConfig.canUploadFile2Dir, true);
			}
		}
		
	}
}
